package com.shensi.adminCollect.task.admin;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONObject;
import com.shensi.adminCollect.domain.station.PayOrder;
import com.shensi.adminCollect.domain.station.SysAppUserInfo;
import com.shensi.adminCollect.domain.station.vo.YunHuaOrderInfo;
import com.shensi.adminCollect.domain.station.vo.YunHuaUserVo;
import com.shensi.adminCollect.mapper.station.AppUserInfoMapper;
import com.shensi.adminCollect.mapper.station.PayOrderMapper;
import com.shensi.adminCollect.service.station.IAppUserInfoService;
import com.shensi.adminCollect.service.station.IPayOrderService;
import com.shensi.common.core.utils.LocalDateTimeUtil;
import com.shensi.common.core.utils.StringUtils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Configuration
@EnableScheduling
@Slf4j
public class SyncYunHuaTask  {

    @Resource
    private IAppUserInfoService appUserInfoService;

    @Resource
    private AppUserInfoMapper appUserInfoMapper;

    @Resource
    private IPayOrderService payOrderService;

    @Resource
    private PayOrderMapper payOrderMapper;




    /**
     * 同步到云化user,并更新yunHuaUserId
     * cron = 0 0/2 * * * ?
     */
    @XxlJob("syncYunHuaUserId")
    private void syncYunHuaUserId(){
        log.info("开始同步yunHuaUserId");
        long l = System.currentTimeMillis();
        List<SysAppUserInfo> notSyncYunHuaUserList = appUserInfoMapper.getNotSyncYunHuaUser();

        if(CollectionUtils.isEmpty(notSyncYunHuaUserList)){
            return;
        }
        //闪付用户 手机号是一长串，eg:fpa2d9476fec7e001  直接修改is_sync_yunhua状态
        for (SysAppUserInfo sysAppUserInfo : notSyncYunHuaUserList) {
            if(StringUtils.isNotEmpty(sysAppUserInfo.getMobilePhone()) && !Validator.isMobile(sysAppUserInfo.getMobilePhone())){
                //修改状态
                appUserInfoMapper.updateIsSyncByPhone(sysAppUserInfo.getMobilePhone());
            }
        }


        List<YunHuaUserVo> yunHuaUserVoList = notSyncYunHuaUserList.stream().filter(m-> StringUtils.isNotEmpty(m.getMobilePhone()) && Validator.isMobile(m.getMobilePhone()))
                .map(m -> {
                YunHuaUserVo yunHuaUserVo = new YunHuaUserVo();
                yunHuaUserVo.setMobilePhone(m.getMobilePhone());
                return yunHuaUserVo;
        }).distinct().collect(Collectors.toList());

        if(CollectionUtils.isEmpty(yunHuaUserVoList)){
            return;
        }

        //4.同步用户到云化

        appUserInfoService.batchUserToYunHua(yunHuaUserVoList);
        long l1 = System.currentTimeMillis();
        log.info("消耗时间{}",l1 - l);

//
//
//        for (SysAppUserInfo user : notSyncYunHuaUserList) {
//            String mobilePhone = user.getMobilePhone();
//            String enterpriseId = user.getStationId().toString();
//            log.info("用户手机号{}", mobilePhone);
//            if(StringUtils.isEmpty(mobilePhone) || !Validator.isMobile(mobilePhone)){
//                continue;
//            }
//            //1 获取云化userid
//            String yunHuaUserId = appUserInfoService.getYunHuaUserId(mobilePhone);
//            if(StringUtils.isEmpty(yunHuaUserId)){
//                log.info("获取yunHuaUserId为空");
//                return;
//            }
//            //2 更新云化userid
//            SysAppUserInfo appUserInfo = new SysAppUserInfo();
//            appUserInfo.setMobilePhone(user.getMobilePhone());
//            appUserInfo.setYunhuaUserId(yunHuaUserId);
//            appUserInfoMapper.updateYunHuaUserIdByPhone(appUserInfo);
//            //4 发送用户信息到云化
//            appUserInfoService.syncYunHuaUser(mobilePhone,enterpriseId);
//            //3 更新标识
//            appUserInfoMapper.updateIsSyncByPhone(mobilePhone);

//        }
    }

    //定时查询云化订单支付状态 0/10 * * * * ?
    @XxlJob("changeOrderStatus")
    public void changeOrderStatus(){
        log.info("查询5分钟内的待支付订单");
        Date now = new Date();
        Date newDate = DateUtil.offset(now, DateField.MINUTE, -5);
        String startTime = DateUtil.format(newDate, "yyyy-MM-dd HH:mm:ss");
        List<YunHuaOrderInfo> payOrderList = payOrderService.selectPayOrderListByStartTime(startTime);
        if(CollectionUtils.isEmpty(payOrderList)){
            return;
        }
        log.info("补偿机制处理订单数量：【{}】", payOrderList.size());
        for (YunHuaOrderInfo yunHuaOrderInfo : payOrderList) {

                //排除非云化支付的订单
                if(StringUtils.isEmpty(yunHuaOrderInfo.getClientOrderNo()) || StringUtils.isEmpty(yunHuaOrderInfo.getClientSerialNo())){
                    continue;
                }

            try {
                String orderStatusRes = payOrderService.getOrderStatus(yunHuaOrderInfo);

                if(StringUtils.isEmpty(orderStatusRes)){
                    continue;
                }

                JSONObject jsonObject = JSONObject.parseObject(orderStatusRes);
                if(Objects.isNull(jsonObject.get("data"))){
                    continue;
                }

                log.info("订单状态【{}】",jsonObject.get("data"));

                String data = jsonObject.get("data").toString();

                JSONObject dataObj = JSONObject.parseObject(data);
                String status = dataObj.get("status").toString();

                log.info("订单状态【{}】", status);
                //如果订单状态是待支付，但是查询为已支付，则手动更新订单状态
                if("0".equals(yunHuaOrderInfo.getStatus()) && "3".equals(status) ){
                    //更新订单状态
                    String transPayNo = dataObj.get("transPayNo").toString();
                    String transInfoNo = dataObj.get("transInfoNo").toString();
                    String payTimeStr = dataObj.getString("payTime");
                    log.info("开始更新订单状态，订单号【{}】", yunHuaOrderInfo.getOrderNo());
                    PayOrder payOrder = new PayOrder();
                    payOrder.setOrderNo(yunHuaOrderInfo.getOrderNo());
                    payOrder.setStatus("1");
                    payOrder.setTransactionId(transPayNo);
                    payOrder.setMerchantsNumber(transInfoNo);
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(payTimeStr)) {
                        try{
                            payOrder.setPayDate(LocalDateTimeUtil.parseDate(LocalDateTime.parse(payTimeStr)));
                        }catch (Exception e){
                            log.error("时间解析失败");
                            log.error(e.getMessage());
                            payOrder.setPayDate(new Date());
                        }
                    }else{
                        payOrder.setPayDate(new Date());
                    }
                    payOrderMapper.updatePayOrderByOrderNo(payOrder);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("补偿机制更新订单出现异常");
            }
        }
    }
}
